package org.doubango.ngn.h264

import android.annotation.TargetApi
import android.os.Build
import com.evendai.loglibrary.Timber
import org.doubango.ngn.media.NgnProxyVideoProducer

import java.util.concurrent.BlockingQueue
import java.util.concurrent.LinkedBlockingQueue


@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
class H264EncoderThread(producer: NgnProxyVideoProducer, val isPortrait: Boolean) : Thread(TAG) {
    @Suppress("SpellCheckingInspection")
    private var mYUVDatasQueue: BlockingQueue<ByteArray> = LinkedBlockingQueue(5)
    private val mH264Encoder = H264Encoder(producer, isPortrait)
    private var frameLossCount: Int = 0

    @Suppress("SpellCheckingInspection")
    fun addYUVDatas(yuvDatas: ByteArray) {
        val offer = mYUVDatasQueue.offer(yuvDatas)
        if (!offer) {
            Timber.e("丢帧：${++frameLossCount}帧")
        }
    }

    override fun run() {
        try {
            while (!isInterrupted) {
                mH264Encoder.encodeYuvToH264(mYUVDatasQueue.take())
            }
        } catch (e: InterruptedException) {
            Timber.w("别慌，线程是正常中断的，线程名称 = ${currentThread().name}")
        } catch (e: Exception) {
            Timber.e(e,"把YUV编码为H264时出现异常")
        }

    }

    fun close() {
        try {
            interrupt()
            mH264Encoder.close()
        } catch (e: Exception) {
            Timber.w(e, "关闭H264编码器时出现异常")
        }
    }

    companion object {
        private val TAG = H264EncoderThread::class.java.simpleName
    }

}
